package com.slz3.business.module.afterSaleManagement.aftApplyOrder.domain;

import com.slz3.business.frame.enums.AuditFlag;
import com.slz3.business.frame.enums.UsingFlag;
import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.redis.Jedis;
import com.slz3.business.frame.redis.RK;
import com.slz3.business.frame.steward.Steward;
import com.slz3.business.frame.util.LocalDT;
import com.slz3.business.frame.util.UUIDUtils;
import com.slz3.business.frame.util.VE;
import com.slz3.business.module.afterSaleManagement.aftApplyOrderLine.domain.AfterSaleDetail;
import com.slz3.business.module.orderManagement.ordOrder.domain.Order;
import com.slz3.business.module.orderManagement.ordOrder.domain.OrderDetailGroup;
import com.slz3.business.module.orderManagement.ordOrder.domain.OrderStatusEnum;
import com.slz3.business.module.orderManagement.ordOrder.enums.OrdOrderStatusEnum;
import com.slz3.business.module.orderManagement.ordOrder.steward.OrdOrderRedisSteward;
import com.slz3.business.module.orderManagement.ordOrderLine.domain.OrderDetail;
import org.springframework.util.MultiValueMap;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

public class AftApplyOrderFactory {

    /**
     * 初始化基础属性值
     */
    public static AftApplyOrder initBaseFields(AftApplyOrder aftApplyOrder) {
        if (aftApplyOrder.getUuid() == null) {
            aftApplyOrder.setUuid(UUIDUtils.generateUUID());
//            aftApplyOrder.setCreateTime(LocalDateTime.now());
//            if (VE.isEmpty(aftApplyOrder.getSerAudit())) {
//                aftApplyOrder.setSerAudit(AuditFlag.WAIT_SUBMIT);
//            }
//            if (VE.isEmpty(aftApplyOrder.getSerUsing())) {
//                aftApplyOrder.setSerUsing(UsingFlag.ENABLE);
//            }
        } else {
            aftApplyOrder.setLastModifyTime(LocalDateTime.now());
        }
        if(VE.isEmpty(aftApplyOrder.getCreateTime())){
            aftApplyOrder.setCreateTime(LocalDateTime.now());
        }
        if (VE.isEmpty(aftApplyOrder.getSerAudit())) {
            aftApplyOrder.setSerAudit(AuditFlag.WAIT_SUBMIT);
        }
        if (VE.isEmpty(aftApplyOrder.getSerUsing())) {
            aftApplyOrder.setSerUsing(UsingFlag.ENABLE);
        }
        return aftApplyOrder;
    }

    /**
     * 初始化基础属性值
     */
    public static AftApplyOrder initBaseFields() {
        return initBaseFields(newTemStyle());
    }

    public static AftApplyOrder newTemStyle() {
        return new AftApplyOrder();
    }

    public static AftApplyOrderCondition newAftApplyOrderCondition(MultiValueMap<String, String> params) {

        AftApplyOrderCondition condition = new AftApplyOrderCondition();

        String uuid = params.getFirst("uuid");
        String createTimeOUTSET = params.getFirst("createTimeOUTSET");
        String createTimeFINISH = params.getFirst("createTimeFINISH");
        String lastModifyTimeOUTSET = params.getFirst("lastModifyTimeOUTSET");
        String lastModifyTimeFINISH = params.getFirst("lastModifyTimeFINISH");
        String serAuditList = params.getFirst("serAuditList");
        List<String> serAuditStateList = params.get("serAuditStateList");
        String serMoneyLeft = params.getFirst("serMoneyLeft");
        String serMoneyRight = params.getFirst("serMoneyRight");

        try {
            condition.setUuid(uuid == null ? null : UUID.fromString(uuid));
            condition.setSerMoneyLeft(serMoneyLeft == null ? null : new BigDecimal(serMoneyLeft));
            condition.setSerMoneyRight(serMoneyRight == null ? null : new BigDecimal(serMoneyRight));
        } catch (Exception e) {
        }
        condition.setCreateTimeOUTSET(VE.isEmpty(createTimeOUTSET) ? null : LocalDT.parseStringToDateTime(createTimeOUTSET, AftApplyOrderCondition.CREATE_TIME_OF_PATTERN));
        condition.setCreateTimeFINISH(VE.isEmpty(createTimeFINISH) ? null : LocalDT.parseStringToDateTime(createTimeFINISH, AftApplyOrderCondition.CREATE_TIME_OF_PATTERN));
        condition.setLastModifyTimeOUTSET(VE.isEmpty(lastModifyTimeOUTSET) ? null : LocalDT.parseStringToDateTime(lastModifyTimeOUTSET, AftApplyOrderCondition.CREATE_TIME_OF_PATTERN));
        condition.setLastModifyTimeFINISH(VE.isEmpty(lastModifyTimeFINISH) ? null : LocalDT.parseStringToDateTime(lastModifyTimeFINISH, AftApplyOrderCondition.CREATE_TIME_OF_PATTERN));
        condition.setSerAuditList(VE.isEmpty(serAuditList) ? null : Arrays.stream(serAuditList.split(",")).map(item -> AuditFlag.valueOf(item)).collect(Collectors.toList()));
        condition.setSerAuditStateList(serAuditStateList);
        return condition;

    }

    public static void updateRedisRecord(List<AftApplyOrder> aftApplyOrderList){
        aftApplyOrderList.stream().forEach(aftApplyOrder -> {
            String afterSaleInfoKey = RK.SERVICE__AFTER_SALE__INFO__AFTER_SALE_UUID__$UUID$.replace("${uuid}", aftApplyOrder.getUuid().toString());
            AfterSale afterSale = AfterSale.builder().build();
            Map<String, Object> afterSaleMap = Jedis.db0.getMap(afterSaleInfoKey);
            Steward.map2Obj(afterSaleMap, afterSale);
            afterSale.setSerCoding(aftApplyOrder.getSerCoding());
            afterSale.setSerAuditState(aftApplyOrder.getSerAuditState());
            if(VE.isNotEmpty(aftApplyOrder.getSerAuditTime()))
                afterSale.setSerAuditTime(LocalDT.getDateTimeAsString(aftApplyOrder.getSerAuditTime(), "yyyy-MM-dd HH:mm:ss"));
            if(VE.isNotEmpty(aftApplyOrder.getSerPayDate()))
                afterSale.setSerPayDate(LocalDT.getDateTimeAsString(aftApplyOrder.getSerPayDate(), "yyyy-MM-dd HH:mm:ss"));

            Jedis.db0.set(afterSaleInfoKey, Steward.obj2Map(afterSale));

            String orderInfoKey = RK.SERVICE__ORDER__INFO__ORDER_UUID__$UUID$.replace("${uuid}",afterSale.getSerOrderId());
            String orderJoinDetailKey = RK.SERVICE__ORDER__JOIN__ORDER_DETAIL__ORDER_UUID__$UUID$.replace("${uuid}",afterSale.getSerOrderId());
            Order order = Order.builder().build();
            Map<String,Object> orderMap = Jedis.db0.getMap(orderInfoKey);
            Steward.map2Obj(orderMap,order);

            List<String> orderDetailUuidList = Jedis.db0.getSet(orderJoinDetailKey).stream().filter(item->item!=null).map(item->item.toString()).collect(Collectors.toList());

            List<String> afterSaleDetailUuidList = Jedis.db0.getSet(RK.SERVICE__AFTER_SALE__JOIN__AFTER_SALE_DETAIL__AFTER_SALE_UUID__$UUID$.replace("${uuid}", afterSale.getUuid())).stream().filter(item -> item != null).map(item -> item.toString()).collect(Collectors.toList());

            List<String> afterSaleDetailInfoKeyList = afterSaleDetailUuidList.stream().map(item -> RK.SERVICE__AFTER_SALE_DETAIL__INFO__AFTER_SALE_DETAIL_UUID__$UUID$.replace("${uuid}", item)).collect(Collectors.toList());

            if(orderDetailUuidList.size() == afterSaleDetailUuidList.size()){
                order.setSerOrderStatus("7");
                order.setSerCloseReason("订单已退款");
                order.setSerCloseTime(LocalDT.getDateTimeAsString(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss"));
                Jedis.db0.set(orderInfoKey,Steward.obj2Map(order));

                List<OrderDetailGroup> orderDetailGroupList = OrdOrderRedisSteward.findOrderDetailGroupByOrder(order);

                orderDetailGroupList.forEach(orderDetailGroup -> {
                    String orderDetailGroupPageKey = "";
                    if(OrdOrderStatusEnum.WAIT_DELEVER.getCode().toString().equals(orderDetailGroup.getSerOrderStatus())){
                        orderDetailGroupPageKey = RK.SERVICE__ORDER_DETAIL_GROUP__SORT__WAIT_DELIVER__MEMBER_UUID__$UUID$.replace("${uuid}",orderDetailGroup.getSerMemberUuid());
                    }else if(OrdOrderStatusEnum.WAIT_RECEIVER.getCode().toString().equals(orderDetailGroup.getSerOrderStatus())){
                        orderDetailGroupPageKey = RK.SERVICE__ORDER_DETAIL_GROUP__SORT__WAIT_RECEIVER__MEMBER_UUID__$UUID$.replace("${uuid}",orderDetailGroup.getSerMemberUuid());
                    }else if(OrdOrderStatusEnum.AL_READY.getCode().toString().equals(orderDetailGroup.getSerOrderStatus())){
                        orderDetailGroupPageKey = RK.SERVICE__ORDER_DETAIL_GROUP__SORT__ALREADY__MEMBER_UUID__$UUID$.replace("${uuid}",orderDetailGroup.getSerMemberUuid());
                    }
                    Jedis.db0.removeFromList(orderDetailGroupPageKey,0,orderDetailGroup.getUuid());
                    orderDetailGroup.setSerCloseTime(order.getSerCloseTime());
                    orderDetailGroup.setSerOrderStatus(order.getSerOrderStatus());
                    orderDetailGroup.setSerCloseReason(order.getSerCloseReason());
                    OrdOrderRedisSteward.closeOrderDetailGroup(orderDetailGroup);
                });
            }

            List<AfterSaleDetail> afterSaleDetailList = Jedis.db0.getListByKey(afterSaleDetailInfoKeyList).stream()
                    .filter(item -> item != null).map(item -> {
                        AfterSaleDetail afterSaleDetail = AfterSaleDetail.builder().build();
                        Map<String, Object> map = (Map) item;
                        Steward.map2Obj(map, afterSaleDetail);
                        afterSaleDetail.setSerCoding(afterSale.getSerCoding());
                        afterSaleDetail.setSerPayDate(afterSale.getSerPayDate());
                        afterSaleDetail.setSerAuditState(afterSale.getSerAuditState());
                        return afterSaleDetail;
                    }).collect(Collectors.toList());

            afterSaleDetailList.stream().forEach(afterSaleDetail ->{
                String orderDetailInfoKey = RK.SERVICE__ORDER_DETAIL__INFO__ORDER_DETAIL_UUID__$UUID$.replace("${uuid}",afterSaleDetail.getSerOrderDetailUuid());
                OrderDetail orderDetail = OrderDetail.builder().build();
                Map<String,Object> orderDetailMap = Jedis.db0.getMap(orderDetailInfoKey);
                Steward.map2Obj(orderDetailMap,orderDetail);
                orderDetail.setRefundStatus(afterSaleDetail.getSerAuditState());

                //modify redis orderDetail
                Jedis.db0.set(orderDetailInfoKey,Steward.obj2Map(orderDetail));

                List<String> orderDetailUuidByGroupList = Jedis.db0.getSet(RK.SERVICE__ORDER_DETAIL_GROUP__JOIN__ORDER_DETAIL__ORDER_DETAIL_GROUP_UUID__$UUID$.replace("${uuid}",orderDetail.getSerOrderDetailGroupUuid())).stream().filter(item->item!=null).map(item->item.toString()).collect(Collectors.toList());
                if(orderDetailUuidByGroupList.size()==afterSaleDetailList.size()){
                    OrderDetailGroup orderDetailGroup = OrderDetailGroup.builder().build();
                    Map<String,Object> orderDetailGroupMap = Jedis.db0.getMap(RK.SERVICE__ORDER_DETAIL_GROUP__INFO__ORDER_DETAIL_GROUP_UUID__$UUID$.replace("${uuid}",orderDetail.getSerOrderDetailGroupUuid()));
                    Steward.map2Obj(orderDetailGroupMap,orderDetailGroup);
//                    List<OrderDetailGroup> orderDetailGroupList = OrdOrderRedisSteward.findOrderDetailGroupByOrder(order);

//                    orderDetailGroupList.forEach(orderDetailGroup -> {
                        String orderDetailGroupPageKey = "";
                        if(OrdOrderStatusEnum.WAIT_DELEVER.getCode().toString().equals(orderDetailGroup.getSerOrderStatus())){
                            orderDetailGroupPageKey = RK.SERVICE__ORDER_DETAIL_GROUP__SORT__WAIT_DELIVER__MEMBER_UUID__$UUID$.replace("${uuid}",orderDetailGroup.getSerMemberUuid());
                        }else if(OrdOrderStatusEnum.WAIT_RECEIVER.getCode().toString().equals(orderDetailGroup.getSerOrderStatus())){
                            orderDetailGroupPageKey = RK.SERVICE__ORDER_DETAIL_GROUP__SORT__WAIT_RECEIVER__MEMBER_UUID__$UUID$.replace("${uuid}",orderDetailGroup.getSerMemberUuid());
                        }else if(OrdOrderStatusEnum.AL_READY.getCode().toString().equals(orderDetailGroup.getSerOrderStatus())){
                            orderDetailGroupPageKey = RK.SERVICE__ORDER_DETAIL_GROUP__SORT__ALREADY__MEMBER_UUID__$UUID$.replace("${uuid}",orderDetailGroup.getSerMemberUuid());
                        }
                        Jedis.db0.removeFromList(orderDetailGroupPageKey,0,orderDetailGroup.getUuid());
                        orderDetailGroup.setSerCloseTime(LocalDT.getDateTimeAsString(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss"));
                        orderDetailGroup.setSerOrderStatus("7");
                        orderDetailGroup.setSerCloseReason("订单已退款");
                        OrdOrderRedisSteward.closeOrderDetailGroup(orderDetailGroup);
//                    });
                    aftApplyOrder.setSerOrderStatus(orderDetailGroup.getSerOrderStatus());
                    Services.aftApplyOrder.modify(aftApplyOrder);
                }

                //roll back stock
                Jedis.db0.incrAndDecr(RK.WMS.simple(orderDetail.getSerItemId()),Long.valueOf(orderDetail.getSerOrderCount()));
                //modify redis afterSaleDetail
                Jedis.db0.set(RK.SERVICE__AFTER_SALE_DETAIL__INFO__AFTER_SALE_DETAIL_UUID__$UUID$.replace("${uuid}", afterSaleDetail.getUuid()), Steward.obj2Map(afterSaleDetail));
            });

        });
    }

    public static AftApplyOrder newAftApplyOrderByAfterSale(AfterSale afterSale){
        AftApplyOrder aftApplyOrder = new AftApplyOrder();
        aftApplyOrder.setUuid(UUID.fromString(afterSale.getUuid()));
        aftApplyOrder.setAfterSaleNo(afterSale.getAfterSaleNo());
        aftApplyOrder.setSerFileUrl(afterSale.getSerFileUrl());
        aftApplyOrder.setSerAfterSaleType(afterSale.getSerAfterSaleType());
        aftApplyOrder.setSerEditorContent(afterSale.getSerEditorContent());
        aftApplyOrder.setSerGoodsStatus(afterSale.getSerGoodsStatus());

        aftApplyOrder.setSerOrderId(UUID.fromString(afterSale.getSerOrderId()));
        aftApplyOrder.setSerOrderNo(afterSale.getSerOrderNo());
        aftApplyOrder.setSerOrderStatus(afterSale.getSerOrderStatus());
        if(VE.isNotEmpty(afterSale.getSerPaymentTime()))
        aftApplyOrder.setSerPaymentTime(LocalDT.parseStringToDateTime(afterSale.getSerPaymentTime(),"yyyy-MM-dd HH:mm:ss"));

        aftApplyOrder.setReceiverName(Optional.ofNullable(afterSale.getReceiverName()).orElse(""));
        aftApplyOrder.setReceiverPhone(Optional.ofNullable(afterSale.getReceiverPhone()).orElse(""));
        aftApplyOrder.setAddressStr(Optional.ofNullable(afterSale.getAddressStr()).orElse(""));
        aftApplyOrder.setAddressDetail(Optional.ofNullable(afterSale.getAddressDetail()).orElse(""));
        aftApplyOrder.setUserName(Optional.ofNullable(afterSale.getUserName()).orElse(""));
        aftApplyOrder.setSerUserId(UUID.fromString(afterSale.getSerUserId()));

        aftApplyOrder.setSerAuditState(afterSale.getSerAuditState());
        aftApplyOrder.setSerUserReason(afterSale.getSerUserReason());
        if (VE.isNotEmpty(afterSale.getSerCreateTime()))
            aftApplyOrder.setSerCreateTime(LocalDT.parseStringToDateTime(afterSale.getSerCreateTime(),"yyyy-MM-dd HH:mm:ss"));
        aftApplyOrder.setSerCoding(Optional.ofNullable(afterSale.getSerCoding()).orElse(""));
        if(VE.isNotEmpty(afterSale.getSerCount()))
            aftApplyOrder.setSerCount(Optional.ofNullable(Integer.valueOf(afterSale.getSerCount())).orElse(null));
        aftApplyOrder.setSerLogisticsNum(Optional.ofNullable(afterSale.getSerLogisticsNum()).orElse(""));
        aftApplyOrder.setSerLogisticsCompany(Optional.ofNullable(afterSale.getSerLogisticsCompany()).orElse(""));
        if(VE.isNotEmpty(afterSale.getSerMoney()))
            aftApplyOrder.setSerMoney(Optional.ofNullable(Double.valueOf(afterSale.getSerMoney())).orElse(null));
        return aftApplyOrder;
    }

}
